const express = require('express');
const router = express.Router();
const formController = require('../controllers/formController');
const { auth, authorize } = require('../middleware/auth');
const { auditLogger, saveBefore } = require('../middleware/audit');
const validate = require('../middleware/validate');
const formValidators = require('../validators/form');
const { Form } = require('../models');

// 更新表单配置 (调试接口，增加鉴权保护)
router.put('/forms/:id/config/debug', 
  auth,
  authorize('admin', 'project_admin'),
  formController.updateFormConfig
);

// 应用认证中间件到所有路由
router.use(auth);

// 获取所有表单列表
router.get('/forms', 
  formController.getAllForms
);

// 创建独立表单（不关联章节）
router.post('/forms', 
  authorize('admin', 'project_admin', 'project_user'),
  validate(formValidators.createForm),
  auditLogger('create', 'form'),
  formController.createStandaloneForm
);

// 获取章节下的表单列表
router.get('/sections/:sectionId/forms', 
  formController.getForms
);

// 在章节下创建表单
router.post('/sections/:sectionId/forms', 
  authorize('admin', 'project_admin', 'project_user'),
  validate(formValidators.createForm),
  auditLogger('create', 'form'),
  formController.createForm
);

// 获取表单详情
router.get('/forms/:id', 
  formController.getForm
);

// 更新表单基本信息
router.put('/forms/:id', 
  authorize('admin', 'project_admin', 'project_user'),
  validate(formValidators.updateForm),
  saveBefore(Form),
  auditLogger('update', 'form'),
  formController.updateForm
);

// 更新表单配置
router.put('/forms/:id/config', 
  authorize('admin', 'project_admin', 'project_user'),
  validate(formValidators.updateFormConfig),
  saveBefore(Form),
  auditLogger('update', 'form'),
  formController.updateFormConfig
);

// 删除表单
router.delete('/forms/:id', 
  authorize('admin', 'project_admin', 'project_user'),
  saveBefore(Form),
  auditLogger('delete', 'form'),
  formController.deleteForm
);

// 复制表单
router.post('/forms/:id/copy', 
  authorize('admin', 'project_admin', 'project_user'),
  formController.copyForm
);

// 字段管理
// 添加字段
router.post('/forms/:id/fields', 
  authorize('admin', 'project_admin', 'project_user'),
  validate(formValidators.addField),
  saveBefore(Form),
  auditLogger('create', 'field'),
  formController.addField
);

// 更新字段
router.put('/forms/:id/fields/:fieldId', 
  authorize('admin', 'project_admin', 'project_user'),
  validate(formValidators.updateField),
  saveBefore(Form),
  auditLogger('update', 'field'),
  formController.updateField
);

// 删除字段
router.delete('/forms/:id/fields/:fieldId', 
  authorize('admin', 'project_admin', 'project_user'),
  saveBefore(Form),
  auditLogger('delete', 'field'),
  formController.deleteField
);

module.exports = router;